﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace CPPEI.WebApi
{
    /// <summary>
    /// 集成
    /// </summary>
    public static class Intergration
    {
        public static class Config
        {
            private static object s_lockObj = new object();
            public static IAuthProvider AuthProvider { get; private set; }

            /// <summary>
            /// 初始化配置
            /// </summary>
            public static void Init()
            {
                if (AuthProvider != null)
                    return;
                lock (s_lockObj)
                {
                    if (AuthProvider != null)
                        return;
                    string configFile = System.Web.HttpContext.Current.Server.MapPath("~/Configs/WebApi.Intergration.config");

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(configFile);
                    XmlNode xAuthMode = xDoc.SelectSingleNode("./WebApi/Authentication");
                    if (xAuthMode != null)
                    {
                        string mode = xAuthMode.Attributes["Mode"].Value.Trim();
                        if (string.Equals(mode, "Forms"))
                        {
                            AuthProvider = new FormsAuthProvider();
                        }
                        else
                        {
                            AuthProvider = new CookieAuthProvider();
                        }
                    }

                    XmlNodeList xInitiators = xDoc.SelectNodes("./WebApi/Initiators/Initiator");
                    for (int index = 0; index < xInitiators.Count; index++)
                    {
                        XmlNode xInitiator = xInitiators[index];
                        string assemblyName = xInitiator.Attributes["Assembly"].Value.Trim();
                        string typeName = xInitiator.Attributes["Type"].Value.Trim();
                        IInitiator oInitiator = System.Reflection.Assembly.Load(assemblyName).CreateInstance(typeName) as IInitiator;
                        if (oInitiator != null)
                        {
                            oInitiator.Init();
                        }
                    }
                }
            }
        }

    }
}
